const db = uniCloud.database()
const collection = db.collection('uni-cms-articles')
const ApiResponse = require('iss-api-response')
const ErrorMessage = ApiResponse.ErrorMessage
const commonMixin = require('common-mixin')

module.exports = {
  ...commonMixin,
  
  /**
   * 获取公告信息
   * @param {number} pageNum 当前页码（select为false时有效）
   * @param {number} pageSize 每页数量（select为false时有效）
   * @returns {object} 返回公告信息列表
   */
  async getNoticeList({pageNum = 1, pageSize = 10}) {
    try {
      // 基础查询条件
      let whereCondition = {article_status: 1}
      let query = collection.where(whereCondition).orderBy('publish_date', 'desc')
      const offset = (pageNum - 1) * pageSize
      res = await query.skip(offset).limit(pageSize).get()
      const countRes = await collection.where(whereCondition).count()
      total = countRes.total

      // 返回数据
      return ApiResponse.success({
        list: res.data,
        total,
        pageNum: pageNum,
        pageSize: pageSize,
        isLogin: !!this.userInfo // 额外返回是否登录状态
      })
      
    } catch (e) {
      console.error(ErrorMessage.GET_NOTICELIST_ERROR, e)
      return ApiResponse.serverError(ErrorMessage.GET_NOTICELIST_ERROR)
    }
  },
  
  /**
     * 根据ID获取公告信息
     * @param {string} id 公告的ID
     * @returns {object} 返回公告信息
     */
    async getNoticeById({id}) {
      try {
  		// 校验 id 是否为有效的字符串
  		if (typeof id!== 'string' || id.trim() === '') {
  		  return ApiResponse.badRequest(ErrorMessage.INVALID_ID)
  		}
        const res = await collection.doc(id).get()
        if (res.data.length === 0) {
          return ApiResponse.notFound(ErrorMessage.NOTICE_NOT_FOUND)
        }
        return ApiResponse.success(res.data[0])
      } catch (e) {
        console.error(ErrorMessage.GET_NOTICE_BY_ID_ERROR, e)
        return ApiResponse.serverError(ErrorMessage.GET_NOTICE_BY_ID_ERROR)
      }
    }
}